<template>
  <div class="category-container">
    <a-card title="文章分类管理" :bordered="false">
      <!-- 操作栏 -->
      <div class="table-operations">
        <a-button type="primary" @click="showAddModal">
          <template #icon><plus-outlined /></template>
          新增分类
        </a-button>
      </div>

      <!-- 分类表格 -->
      <a-table
        :columns="columns"
        :data-source="categories"
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <!-- 操作列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个分类吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑分类弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入分类名称" />
        </a-form-item>

        <a-form-item label="分类编码" name="code">
          <a-input v-model:value="formState.code" placeholder="请输入分类编码" />
        </a-form-item>

        <a-form-item label="分类图标" name="icon">
          <a-input v-model:value="formState.icon" placeholder="请输入分类图标" />
        </a-form-item>

        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="formState.sort" :min="0" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  getArticleCategories,
  createArticleCategory,
  updateArticleCategory,
  deleteArticleCategory
} from '@/api/article';

export default defineComponent({
  components: {
    PlusOutlined
  },
  setup() {
    const categories = ref([]);
    const loading = ref(false);
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const modalTitle = ref('新增分类');
    const formRef = ref();
    const isEdit = ref(false);
    const currentId = ref(null);

    // 表单数据
    const formState = reactive({
      name: '',
      code: '',
      icon: '',
      sort: 0
    });

    // 表单验证规则
    const rules = {
      name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
      code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }]
    };

    // 表格列定义
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 80
      },
      {
        title: '分类名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '分类编码',
        dataIndex: 'code',
        key: 'code'
      },
      {
        title: '图标',
        dataIndex: 'icon',
        key: 'icon'
      },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        width: 100
      },
      {
        title: '操作',
        key: 'action',
        width: 150
      }
    ];

    // 获取分类列表
    const fetchCategories = async () => {
      loading.value = true;
      try {
        const res = await getArticleCategories();
        if (res.code === 0) {
          categories.value = res.data;
        } else {
          message.error(res.message || '获取分类失败');
        }
      } catch (error) {
        console.error('获取分类失败:', error);
        message.error('获取分类失败');
      } finally {
        loading.value = false;
      }
    };

    // 显示新增分类弹窗
    const showAddModal = () => {
      isEdit.value = false;
      currentId.value = null;
      modalTitle.value = '新增分类';
      resetForm();
      modalVisible.value = true;
    };

    // 显示编辑分类弹窗
    const showEditModal = (record) => {
      isEdit.value = true;
      currentId.value = record.id;
      modalTitle.value = '编辑分类';
      
      // 填充表单数据
      formState.name = record.name;
      formState.code = record.code;
      formState.icon = record.icon || '';
      formState.sort = record.sort || 0;
      
      modalVisible.value = true;
    };

    // 处理弹窗确认
    const handleModalOk = async () => {
      try {
        await formRef.value.validate();
        
        modalLoading.value = true;
        const data = { ...formState };
        
        if (isEdit.value) {
          // 更新分类
          const res = await updateArticleCategory(currentId.value, data);
          if (res.code === 0) {
            message.success('更新成功');
            modalVisible.value = false;
            fetchCategories();
          } else {
            message.error(res.message || '更新失败');
          }
        } else {
          // 创建分类
          const res = await createArticleCategory(data);
          if (res.code === 0) {
            message.success('创建成功');
            modalVisible.value = false;
            fetchCategories();
          } else {
            message.error(res.message || '创建失败');
          }
        }
      } catch (error) {
        console.error('表单验证失败:', error);
      } finally {
        modalLoading.value = false;
      }
    };

    // 处理弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
      resetForm();
    };

    // 重置表单
    const resetForm = () => {
      formState.name = '';
      formState.code = '';
      formState.icon = '';
      formState.sort = 0;
      
      // 重置表单验证
      if (formRef.value) {
        formRef.value.resetFields();
      }
    };

    // 处理删除分类
    const handleDelete = async (record) => {
      try {
        const res = await deleteArticleCategory(record.id);
        if (res.code === 0) {
          message.success('删除成功');
          fetchCategories();
        } else {
          message.error(res.message || '删除失败');
        }
      } catch (error) {
        console.error('删除分类失败:', error);
        message.error('删除失败');
      }
    };

    onMounted(() => {
      fetchCategories();
    });

    return {
      categories,
      loading,
      columns,
      modalVisible,
      modalLoading,
      modalTitle,
      formRef,
      formState,
      rules,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      handleDelete
    };
  }
});
</script>

<style scoped>
.category-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
}

.text-danger {
  color: #ff4d4f;
}
</style> 